package com.topInterview;

/**
 * @Author: huangzhigao
 * @Date: 2022/2/26 11:00
 */
public class leecode395 {
    public int longestSubstring(String s, int k) {
        int max = 0;
        char[] chars = s.toCharArray();
        int N = chars.length;
        for (int require = 1; require <= 26; require++) {
            int[] ints = new int[26];
            int count = 0;
            int satisfy = 0;
            int R = -1;
            for (int L = 0; L < N; L++) {
                while (R + 1 < N && !(count == require && ints[chars[R + 1] - 'a'] == 0)) {
                    R++;
                    if (ints[chars[R] - 'a'] == 0) {
                        //当前元素第一次来
                        count++;
                    }
                    if (ints[chars[R] - 'a'] == k - 1) {
                        //当前元素已有的个数为k-1代表加上当前的就满了
                        satisfy++;
                    }
                    ints[chars[R] - 'a']++;
                }
                if (satisfy == require) {
                    //满足条件，统计一下答案
                    max = Math.max(max, R - L + 1);
                }
                if (ints[chars[L] - 'a'] == 1) {
                    //如果接下来L要往下走，当前的位置为1的话，元素的种类需要减少一种
                    count--;
                }

                if (ints[chars[L] - 'a'] == k) {
                    //如果当前元素个数正好为K,则在L退出窗口时，需要-1
                    satisfy--;
                }
                ints[chars[L] - 'a']--;

            }
        }

        return max;
    }
}
